#!/usr/bin/env bash

set -ex

CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD)

invalidationResponse=''
if [[ "$GITHUB_REF_TYPE" == "tag" && "$GITHUB_REF_NAME" = v* ]]; then
  invalidationResponse=$(aws cloudfront create-invalidation --distribution-id "$CLOUDFRONT_DISTRIBUTION" --paths "/*")
elif [[ "$CURRENT_BRANCH" == "prerelease/"* ]]; then
  invalidationResponse=$(aws cloudfront create-invalidation --distribution-id "$CLOUDFRONT_DISTRIBUTION" --paths "/channels/beta/*" "/channels/versions/*")
else
  echo "Not on stable or beta release, skipping invalidate cdn cache"
fi

if [[ "$invalidationResponse" != '' ]]; then
  invalidationId=$(echo "$invalidationResponse" |  grep Id  | awk -F'"' '{ print $4}')
  aws cloudfront wait invalidation-completed --id "$invalidationId" --distribution-id "$CLOUDFRONT_DISTRIBUTION"
fi
